/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.centrodata.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.centrodata.dao.PriorityDao;
import br.com.centrodata.model.Priority;

/**
 *
 * @author João Fernandes Lima Neto
 */
@Resource
public class PriorityController implements GenericController<Priority> {

    private Result     result;
    private Validator  validator;
    private PriorityDao dao;

    public PriorityController(Result result, Validator validator, PriorityDao dao) {
        this.result = result;
        this.validator = validator;
        this.dao = dao;
    }

    @Path("/priority/index")
    @Get
    @Override
    public void index() {
        result.include("priority", dao.search());
    }

    @Path("/priority/new")
    @Get
    @Override
    public void form() {
    }

    @Path("/priority/{priority.id}")
    @Get
    @Override
    public void form(Priority priority) {
        result.include("priority", dao.search(priority.getId()));
    }

    @Path("/priority/delete/{priority.id}")
    @Get
    @Override
    public void delete(Priority priority) {
        try{
            dao.del(priority);
            result.include("notice", "Registro deletado com sucesso");
            result.redirectTo(this).index();
        }catch(Exception e){
            result.include("error", "Ocorreu um erro ao tentar deletar o registro");
            result.redirectTo(this).index();
        }
    }

    @Path("/priority/save")
    @Post
    @Override
    public void save(Priority priority) {
        
        boolean isEdit = priority.getId() > 0;
        
        /* se estiver Editando */
        if(isEdit){
            this.dao.update(priority);
            result.include("notice", "Prioridade [" + priority.getDescricao() + "] atualizado com sucesso.");
        }else{
            this.dao.add(priority);
            result.include("notice", "Prioridade [" + priority.getDescricao() + "] inserido com sucesso.");
        }
        result.forwardTo(this).index();
    }
    
}
